import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import { Form, Input, Select, Upload, Icon, Spin, Cascader, Radio, Checkbox } from 'antd';
import _ from 'lodash';

import ContentLayout from '@/component/common/ContentLayout';
import MModal from '@/component/common/MModal';
import style from './houseAdd.scss';
import ApiHelper from '@/store/ApiHelper';
import { common_address_city_json } from '@/common/address_city_json';
import { search_community, house_get_dtree_list, upload_picture, house_add, house_pre_edit } from '@/constants/ApiTypes';
import { API_URL } from '@/config';

const mConfirm = MModal.confirm;
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const { TextArea } = Input;

import BrokerListMini from '@/store/BrokerListMini';

class HouseTypeSelectGroup extends Component {
    constructor(props) {
        super(props);
        const value = this.props.value || {};
        this.state = {
            shi: value.shi || '0',
            ting: value.ting || '0',
            wei: value.wei || '0'
        };
    }
    static propTypes = {
        onChange: PropTypes.func,
        value: PropTypes.any
    };
    componentWillReceiveProps(nextProps) {
        if ('value' in nextProps) {
            const value = nextProps.value;
            this.setState(value);
        }
    }
    handleChange = (name, value) => {
        this.setState({ [name]: value });
        this.triggerChange({ [name]: value });
    };
    triggerChange = (changedValue) => {
        const onChange = this.props.onChange;
        if (onChange) {
            onChange(Object.assign({}, this.state, changedValue));
        }
    };
    render() {
        const { shi, ting, wei } = this.state;
        const { handleChange } = this;
        const _style_select = { width: 50, display: 'inline-block', margin: '0 3px' };
        return (
            <div>
                <Select size="small" style={_style_select} value={shi} onChange={value => handleChange('shi', value)}>
                    <Option value="0">0</Option>
                    <Option value="1">1</Option>
                    <Option value="2">2</Option>
                    <Option value="3">3</Option>
                    <Option value="4">4</Option>
                    <Option value="5">5</Option>
                    <Option value="6">6</Option>
                    <Option value="7">7</Option>
                    <Option value="8">8</Option>
                </Select>
                <span className={style['unit-label']}>室</span>
                <Select size="small" style={_style_select}value={ting} onChange={value => handleChange('ting', value)}>
                    <Option value="0">0</Option>
                    <Option value="1">1</Option>
                    <Option value="2">2</Option>
                    <Option value="3">3</Option>
                    <Option value="4">4</Option>
                </Select>
                <span className={style['unit-label']}>厅</span>
                <Select size="small" style={_style_select} value={wei} onChange={value => handleChange('wei', value)}>
                    <Option value="0">0</Option>
                    <Option value="1">1</Option>
                    <Option value="2">2</Option>
                    <Option value="3">3</Option>
                    <Option value="4">4</Option>
                </Select>
                <span className={style['unit-label']}>卫</span>
            </div>
        );
    }
}

class HouseFloorGroup extends Component {
    constructor(props) {
        super(props);
        const value = this.props.value || {};
        this.state = {
            house_floor: value.house_floor || 0,
            floors: value.floors || 0
        };
    }
    static propTypes = {
        onChange: PropTypes.func,
        value: PropTypes.any
    };
    componentWillReceiveProps(nextProps) {
        if ('value' in nextProps) {
            const value = nextProps.value;
            this.setState(value);
        }
    }
    handleChange = (name, value) => {
        const number = parseInt(value || 0, 10);
        if (isNaN(number)) {
            return;
        }
        this.setState({ [name]: number });
        this.triggerChange({ [name]: number });
    };
    triggerChange = (changedValue) => {
        const onChange = this.props.onChange;
        if (onChange) {
            onChange(Object.assign({}, this.state, changedValue));
        }
    };
    render() {
        const { house_floor, floors } = this.state;
        const { handleChange } = this;
        const _style = { width: 35, display: 'inline-block', margin: '0 3px' };
        return (
            <div>
                <span className={style['unit-label']}>第</span>
                <Input style={_style} value={house_floor} onChange={e => handleChange('house_floor', e.target.value)}/>
                <span className={style['unit-label']}>层/共</span>
                <Input style={_style}  value={floors} onChange={e => handleChange('floors', e.target.value)}/>
                <span className={style['unit-label']}>层</span>
            </div>
        );
    }
}

@observer class HouseAdd extends Component {
    static propTypes = {
        form: PropTypes.any
    };
    defaultState = {
        cityCode: '330100',
        spinning: true,
        housePublishKey: false,
        communityList: [],
        community_name: '',
        previewVisible: false,
        previewImage: '',
        images: '',
        fileList: []
    };
    state = this.defaultState;
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    async componentDidMount() {
        this._isMounted = true;
        BrokerListMini.getInfo();
        await this.getHousePublishKey(this.state.cityCode);
        this._setState({ spinning: false });
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    //获取房源发布数据字典
    getHousePublishKey = async cityCode => {
        if (cityCode == '') return MModal.success({ title: '错误提示', content: '请先选择城市！' });
        this._setState({ housePublishKey: false });
        const data = {
            city_code: this.state.cityCode
        };
        const result = await ApiHelper.requestPost(house_get_dtree_list, data);
        if (result.status) {
            this._setState({ housePublishKey: result.info });
        }
    };
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };
    handleChange = ({ fileList }) => {
        fileList = fileList.slice(0, 10);
        fileList.forEach((val, index) => {
            if (val.status == 'done' && val.response && !val.response.status) {
                fileList[index].status = 'error';
                MModal.success({ title: '上传失败', content: val.response.info, duration: 1.5 })
            }
        });
        this.fileChange(fileList);
        this.setState({ fileList });
    };
    //返回生成上传成功图片id数组
    fileChange = fileList => {
        let newFileList = [];
        fileList.forEach(val => {
            if (val.response && val.response.status) {
                newFileList.push(val.response.info[0].id);
            }
        });
        const imgs =  newFileList.join(',');
        this.props.form.setFieldsValue({ imgs });
        this.setState({ images: imgs });
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                const data = {
                    broker_id: values.broker_id,
                    imgs: values.imgs,
                    community_code: values.community_code,
                    rent_type: values.rent_type,
                    contact_name: values.contact_name,
                    contact_phone: values.contact_phone,
                    rent: values.rent * 100,
                    size: values.size,
                    unit: `${values.unit.shi},${values.unit.ting},${values.unit.wei}`,
                    house_floor: values.house_floor.house_floor,
                    floors: values.house_floor.floors,
                    house_decoration: values.house_decoration,
                    house_pay: values.house_pay,
                    house_feature: values.house_feature.join(','),
                    house_device: values.house_device.join(','),
                    house_dir: values.house_dir,
                    abstract: values.abstract,
                    title: values.title,
                    entrust_money: 'entrust_money' in values ? values.entrust_money * 100 : 0
                };
                const result = await ApiHelper.requestPost(house_add, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '发布成功' });
                    //重置表单
                    this.props.form.resetFields();
                    this._setState(this.defaultState);
                    await this.getHousePublishKey(this.defaultState.cityCode);
                    this._setState({ spinning: false });
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            } else {
                for ( let key in err ) {
                    return MModal.success({ title: '错误提示', content: err[key].errors[0].message });
                }
            }
        });
    };
    checkPrice = (rule, value, callback) => {
        if (value > 0) {
            callback();
            return;
        }
        callback('金额必须大于0!');
    };
    checkArea = (rule, value, callback) => {
        if (value > 0) {
            callback();
            return;
        }
        callback('建筑面积必须大于0!');
    };
    checkEntrustMoney = (rule, value, callback) => {
        const is_pay_broker = this.props.form.getFieldValue('is_pay_broker');
        if (!is_pay_broker) {
            callback();
        } else {
            return this.checkPrice(rule, value, callback);
        }
    };
    search_community = async value => {
        this.setState({ community_name: value });
        const _r = _.find(this.state.communityList, { community_name: value });
        if (_r !== undefined) {
            return this.props.form.setFieldsValue({ community_code: _r.community });
        }
        const data = {
            city: this.state.cityCode,
            kword: value,
            max: 10
        };
        const result = await ApiHelper.requestPost(search_community, data);
        if (result.status) {
            this._setState({ communityList: result.info });
        }
    };
    citySelect = value => {
        let cityCode = '';
        if (value !== '') {
            cityCode = value.length > 1 ? `${value[1]}` : `${value[0]}`;
        }
        this.setState({
            cityCode,
            housePublishKey: false
        });
        if (value != '') this.getHousePublishKey(cityCode);
    };
    selectAllDevice = all => {
        if (all) {
            const selected = this.state.housePublishKey.house_device.map(val => `${val.id}`);
            this.props.form.setFieldsValue({ house_device: selected });
        } else {
            this.props.form.setFieldsValue({ house_device: [] });
        }
    };
    checkTitle = (rule, value, callback) => {
        if (value.length > 2 && value.length <= 60 ) {
            callback();
            return;
        }
        callback('房源标题字数请在2-60之间!');
    };
    changeBroker = value => {
        const brokerListMini = BrokerListMini.info;
        const result = _.find(brokerListMini, { uid: parseInt(value) });
        this.props.form.setFieldsValue({ contact_name: result.realname, contact_phone: result.mobile });
    };
    render() {
        const { communityList, housePublishKey, fileList, previewVisible, previewImage, community_name } = this.state;
        const { getFieldDecorator, getFieldValue } = this.props.form;
        if (housePublishKey === false) {
            return (
                <ContentLayout navTitle="录入房源">
                    <div className={style['house-add-wrap']}>
                        <div className={style['center-wrap']}>
                            <Form>
                                <FormItem>
                                    <h2>一、填写基本信息<span>(带*号为必填或必选项)</span></h2>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="所在城市"
                                >
                                    <Cascader style={{ width: 200 }} options={common_address_city_json} placeholder="请选择城市" onChange={this.citySelect}/>
                                </FormItem>
                            </Form>
                        </div>
                    </div>
                </ContentLayout>
            );
        }
        const communityOptions = communityList.map(val => <Option key={val.community} value={val.community_name}>{val.community_name}</Option>);
        const houseOrientationRadios = housePublishKey.house_orientation.map(val => <Radio key={val.id} value={`${val.id}`}>{val.name}</Radio>);
        const houseDecorationRadios = housePublishKey.house_decoration.map(val => <Radio key={val.id} value={`${val.id}`}>{val.name}</Radio>);
        const houseDeviceOptions = housePublishKey.house_device.map(val => {
            return { label: val.name, value: `${val.id}` };
        });
        const houseFeatureOptions = housePublishKey.house_feature.map(val => {
            return { label: val.name, value: `${val.id}` };
        });
        const housePayTypeRadios = housePublishKey.house_pay.map(val => <Radio key={val.id} value={`${val.id}`}>{val.name}</Radio>);
        const brokerListMini = BrokerListMini.info;
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.uid}`}>{val.realname}</Option>;
        });

        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传图片</div>
            </div>
        );
        return (
            <ContentLayout navTitle="录入房源">
                <div className={style['house-add-wrap']}>
                    <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                        <div className={style['center-wrap']}>
                            <Form onSubmit={this.handleSubmit}>
                                <FormItem>
                                    <h2>一、填写基本信息<span>(带*号为必填或必选项)</span></h2>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="所在城市"
                                >
                                    <Cascader style={{ width: 200 }} defaultValue={['330000', '330100']} options={common_address_city_json}
                                        placeholder="请选择城市" onChange={this.citySelect}/>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 7 }}
                                    label="小区名称"
                                >
                                    {getFieldDecorator('community_code', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '必须在下拉框中选择小区！'
                                        }]
                                    })(
                                        <Input type="hidden"/>
                                    )}
                                    <Select
                                        mode="combobox"
                                        placeholder="请输入小区名"
                                        notFoundContent="无法找到"
                                        defaultActiveFirstOption={false}
                                        showArrow={false}
                                        filterOption={false}
                                        style={{ width: 200 }}
                                        value={community_name}
                                        onChange={this.search_community}
                                    >
                                        {communityOptions}
                                    </Select>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="户型"
                                >
                                    {getFieldDecorator('unit', {
                                        initialValue: { shi: '0', ting: '0', wei: '0' },
                                        rules: [{
                                            required: true, message: '请选择户型！'
                                        }]
                                    })(
                                        <HouseTypeSelectGroup/>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 6 }}
                                    label="建筑面积"
                                >
                                    {getFieldDecorator('size', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请填写建筑面积！'
                                        }, {
                                            validator: this.checkArea
                                        }]
                                    })(
                                        <Input style={{ width: 110 }} />
                                    )}
                                    <span className={style['unit-label']}>平方米</span>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 6 }}
                                    label="租金"
                                >
                                    {getFieldDecorator('rent', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请填写月租金！'
                                        }, {
                                            validator: this.checkPrice
                                        }]
                                    })(
                                        <Input style={{ width: 110 }} />
                                    )}
                                    <span className={style['unit-label']}>元/月</span>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 7 }}
                                    label="出租方式"
                                >
                                    {getFieldDecorator('rent_type', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择出租方式！'
                                        }]
                                    })(
                                        <RadioGroup>
                                            <Radio value="1">整租</Radio>
                                            <Radio value="2">主卧</Radio>
                                            <Radio value="3">次卧</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 16 }}
                                    label="付款方式"
                                >
                                    {getFieldDecorator('house_pay', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择付款方式！'
                                        }]
                                    })(
                                        <RadioGroup style={{ width: 500 }}>
                                            {housePayTypeRadios}
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="是否付佣"
                                >
                                    {getFieldDecorator('is_pay_broker', {
                                        initialValue: false,
                                        rules: [{
                                            required: true, message: '请选择是否付佣！'
                                        }]
                                    })(
                                        <RadioGroup>
                                            <Radio value={false}>否</Radio>
                                            <Radio value={true}>是</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                {getFieldValue('is_pay_broker') &&
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="佣金"
                                >
                                    {getFieldDecorator('entrust_money', {
                                        initialValue: 0,
                                        rules: [{
                                            required: true, message: '请填写佣金！',
                                            validator: this.checkEntrustMoney
                                        }]
                                    })(
                                        <Input style={{ width: 50 }}/>
                                    )}
                                    <span className={style['unit-label']}>成功租出后向经纪人支付佣金{getFieldValue('entrust_money')}元</span>
                                </FormItem>}
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="楼层"
                                >
                                    {getFieldDecorator('house_floor', {
                                        initialValue: { house_floor: 0, floors: 0 },
                                        rules: [{
                                            required: true, message: '请输入楼层与总楼层！'
                                        }]
                                    })(
                                        <HouseFloorGroup/>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="装修"
                                >
                                    {getFieldDecorator('house_decoration', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择装修程度！'
                                        }]
                                    })(
                                        <RadioGroup>
                                            {houseDecorationRadios}
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="朝向"
                                >
                                    {getFieldDecorator('house_dir', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择朝向！'
                                        }]
                                    })(
                                        <RadioGroup>
                                            {houseOrientationRadios}
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="房屋配套"
                                >
                                    <a className={style['btn-default']} href="javascript:void(0);"
                                        onClick={() => this.selectAllDevice(true)}>全选</a>
                                    <a className={style['btn-default']} href="javascript:void(0);"
                                        onClick={() => this.selectAllDevice(false)}>全不选</a>
                                    {getFieldDecorator('house_device', {
                                        initialValue: []
                                    })(
                                        <CheckboxGroup options={houseDeviceOptions}/>
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="房源特色"
                                >
                                    {getFieldDecorator('house_feature', {
                                        initialValue: []
                                    })(
                                        <CheckboxGroup options={houseFeatureOptions}/>
                                    )}
                                </FormItem>
                                <FormItem>
                                    <h2>一、填写图文信息<span>(带*号为必填或必选项)</span></h2>
                                </FormItem>
                                <FormItem>
                                    <div className={style['tip-box']}>
                                        <span>温馨提示</span>
                                        <p>1、请不要盗用他人房源描述、图片。</p>
                                        <p>2、请不要上传过小、过大、不清楚、不真实的图片</p>
                                        <p>3、限上传jpg、png、gif格式</p>
                                    </div>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="房源标题"
                                >
                                    <span className={style['item-tip']}>很重要，一个好的推荐广告，可以极大的提升房源的点击量！</span>
                                    {getFieldDecorator('title', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请填写房源标题！'
                                        }, {
                                            validator: this.checkTitle
                                        }]
                                    })(
                                        <Input />
                                    )}
                                    <span className={style['item-tip-bottom']}>例：小区中心花园边，赠送十平米的大露台，非常稀缺！投资自住皆宜</span>
                                    <span className={style['item-limit']}>限2-25个中文字</span>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="详细描述"
                                >
                                    {getFieldDecorator('abstract', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请填写详细描述！'
                                        }]
                                    })(
                                        <TextArea rows={5}/>
                                    )}
                                    <span className={style['item-limit']}>200-500字最佳</span>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="房屋图片"
                                >
                                    {getFieldDecorator('imgs', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请上传房屋图片！'
                                        }]
                                    })(
                                        <Input type="hidden" />
                                    )}
                                    <span>注：请勿上传携带其他网站“水印”的图片，以及过小、看不清楚的图片，否则系统将自动删除。限jpg、png、gif格式。支持多图上传，最多可以上传10张。</span>
                                    <div className={style['house-images']}>
                                        <div className="repair-upload">
                                            <Upload
                                                action={`${API_URL}/${upload_picture}`}
                                                listType="picture-card"
                                                fileList={fileList}
                                                onPreview={this.handlePreview}
                                                onChange={this.handleChange}
                                                multiple
                                                accept=".jpg, .png, .gif"
                                                name="image"
                                                data={{ type: 'house' }}
                                            >
                                                {fileList.length >= 10 ? null : uploadButton}
                                            </Upload>
                                            <MModal visible={previewVisible} onClose={this.handleCancel} showMask width={520} height={520} zIndex={101}>
                                                <div className="image-preview-modal">
                                                    <img alt="图片预览" src={previewImage} />
                                                </div>
                                            </MModal>
                                        </div>
                                    </div>
                                </FormItem>
                                <FormItem>
                                    <h2>三、选择发布人<span>(带*号为必填或必选项)</span></h2>
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="选择经纪人">
                                    {getFieldDecorator('broker_id', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择经纪人！'
                                        }]
                                    })(
                                        <Select placeholder="选择经纪人" style={{ width: 200 }} onChange={this.changeBroker}>
                                            {brokerOptionList}
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem>
                                    {getFieldDecorator('contact_name', {
                                        initialValue: ''
                                    })(
                                        <Input type="hidden" />
                                    )}
                                </FormItem>
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 12 }}
                                    label="手机号">
                                    {getFieldDecorator('contact_phone', {
                                        initialValue: '',
                                        rules: [{
                                            required: true, message: '请选择经纪人！'
                                        }]
                                    })(
                                        <Input disabled style={{ width: 200 }} />
                                    )}
                                </FormItem>
                                <FormItem style={{ textAlign: 'center' }}>
                                    <button className={style['submit-btn']} type="submit">确认发布</button>
                                    <a className={style['submit-btn']} href="javascript:void(0);" onClick={() => { window.history.go(-1) }}>返回</a>
                                </FormItem>
                            </Form>
                        </div>
                    </Spin>
                </div>
            </ContentLayout>
        );
    }
}

const FilterWrapped = Form.create()(HouseAdd);

export default FilterWrapped;